package com.matt.service.Photo.impl;

import com.matt.commons.exception.BusinessException;
import com.matt.domain.Children;
import com.matt.domain.Classes;
import com.matt.domain.photoalbum.Photo;
import com.matt.domain.photoalbum.PhotoAlbum;
import com.matt.domain.rel.RelClassesChildren;
import com.matt.foundation.model.ErrorCode;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.ClassesRepository;
import com.matt.repository.photoAlbum.PhotoAlbumRepository;
import com.matt.repository.photoAlbum.PhotoRepository;
import com.matt.repository.rel.RelClassesChildrenRepository;
import com.matt.service.Photo.PhotoAlbumService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class PhotoAlbumServiceImpl implements PhotoAlbumService {

    @Autowired
    PhotoAlbumRepository photoAlbumRepository;

    @Autowired
    PhotoRepository photoRepository;

    @Autowired
    ChildrenRepository childrenRepository;

    @Autowired
    RelClassesChildrenRepository relClassesChildrenRepository;

    @Autowired
    ClassesRepository classesRepository;

    @Override
    public PhotoAlbum getByChildrenId(String areaId, String childrenId,Integer type){

        PhotoAlbum ret = photoAlbumRepository.getOneByAreaIdAndChildrenIdAndType(areaId, childrenId,type);

//        if (ret == null){
//            Children c = childrenRepository.getOne(childrenId);
//            if (c == null){
//                throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
//            }
//
//            String albumName = c.getName() + "的相册";
//            ret = photoAlbumRepository.getOneByAreaIdAndClassIdIsNullAndTitle(areaId, albumName);
//            if (ret == null){
//                ret = new PhotoAlbum();
//
//                ret.setAreaId(areaId);
//                ret.setTitle(albumName);
//                ret.setContent("系统自动生成");
//            }
//
//            ret.setChildrenId(childrenId);
//
//            photoAlbumRepository.save(ret);
//        }

        return ret;
    }

    @Override
    public PhotoAlbum get(String areaId, String albumId,Integer type) {
        PhotoAlbum ret = photoAlbumRepository.getOneByAreaIdAndIdAndTypeAndDeletedIsFalse(areaId, albumId,type);

        if (ret == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "相册不存在");
        }

        return ret;
    }

    @Override
    public List<PhotoAlbum> list(String areaId, String classId,Integer type) {
        if (StringUtils.isNotEmpty(classId)){
            //班级相册
            List<PhotoAlbum>  photoAlbumList = photoAlbumRepository.findAllByAreaIdAndClassIdAndTypeAndDeletedIsFalseOrderBySortDesc(areaId, classId,type);

            //追加班级小朋友的相册
//            List<Children> childrenList =  childrenRepository.findAllChildrenByAreaIdAndClassId(areaId, classId);
//            List<PhotoAlbum> albumList = getPhotoAlbum(childrenList, photoAlbumList, null);
//            photoAlbumList.addAll(albumList);

            return  photoAlbumList;
        }

        //学生列表
//        List<Children> childrenList =  childrenRepository.findByAreaIdAndStatus(areaId,1);
        //相册
        List<PhotoAlbum>  photoAlbumList = photoAlbumRepository.findAllByAreaIdAndTypeAndDeletedIsFalseOrderBySortDesc(areaId,type);
//        List<PhotoAlbum> albumList = getPhotoAlbum(childrenList,photoAlbumList, null);
//        photoAlbumList.addAll(albumList);
        return  photoAlbumList;
    }


    @Override
    public List<PhotoAlbum> listByClassChildren(String areaId, String classId,Integer type) {
        Classes classes = classesRepository.findFirstByAreaIdAndIdAndDeletedIsFalse(areaId, classId);

        if (classes == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST,  "指定班级不存在");
        }

        List<PhotoAlbum>  photoAlbumList = photoAlbumRepository.findAllByAreaIdAndChildrenInClass(areaId, classId,type);
//        Map<String, PhotoAlbum> childrenAlbumCache = photoAlbumList.stream().collect(Collectors.toMap(PhotoAlbum::getChildrenId, o->o));
//
//        List<Children> childrenList =  childrenRepository.findAllChildrenByAreaIdAndClassId(areaId, classId);

//        for (Children c : childrenList){
//            if (childrenAlbumCache.get(c.getId()) != null){
//                continue;
//            }
//
//            PhotoAlbum album = getByChildrenId(c.getAreaId(), c.getId(),type);
//            photoAlbumList.add(0, album);
//        }

        return photoAlbumList;
    }

    List<PhotoAlbum> getPhotoAlbum(List<Children> childrenList, List<PhotoAlbum>  photoAlbumList, String classId){
        List<PhotoAlbum> albumList = new ArrayList<>();
        List<RelClassesChildren> classesChildrenList = new ArrayList<>();

        if (StringUtils.isBlank(classId)){
            List<String> childrenId =  childrenList.stream().map(k -> k.getId()).collect(Collectors.toList());
            classesChildrenList = relClassesChildrenRepository.findByChildrenIdIn(childrenId);
        }

        for (int i = 0; i < childrenList.size(); i++) {
            boolean v = true;
            for (int j = 0; j < photoAlbumList.size(); j++) {
                if (StringUtils.equals(childrenList.get(i).getId(),photoAlbumList.get(j).getChildrenId())){
                    v = false;
                }
            }
            if (v){
                PhotoAlbum photoAlbum = new PhotoAlbum();
                photoAlbum.setChildrenId(childrenList.get(i).getId());
                photoAlbum.setContent(childrenList.get(i).getName());
                photoAlbum.setAreaId(childrenList.get(i).getAreaId());
                photoAlbum.setTitle(childrenList.get(i).getName());
                if (null == classId){
                    if (classesChildrenList.size() > 0){
                        for (int j = 0; j < classesChildrenList.size(); j++) {
                            if (StringUtils.equals(childrenList.get(i).getId(),classesChildrenList.get(j).getChildrenId())){
                                classId = classesChildrenList.get(j).getClassesId();
                                continue;
                            }
                        }
                    }
                }
                photoAlbum.setClassId(classId);
                photoAlbum.setCover(childrenList.get(i).getImgUrl());
                albumList.add(photoAlbum);
            }
        }
        photoAlbumRepository.saveAll(albumList);
        return albumList;
    }
    @Override
    @Transactional
    public PhotoAlbum add(PhotoAlbum album) {
        PhotoAlbum photoAlbum = new PhotoAlbum();

        photoAlbum.setAreaId(album.getAreaId());
        photoAlbum.setClassId(album.getClassId());
        photoAlbum.setStaffId(album.getStaffId());
        photoAlbum.setTitle(album.getTitle());
        photoAlbum.setContent(album.getContent());
        photoAlbum.setSort(album.getSort());
        photoAlbum.setPrivated(album.getPrivated());
        photoAlbum.setCover(album.getCover());
        photoAlbum.setChildrenId(album.getChildrenId());
        photoAlbum.setType(album.getType());

        photoAlbumRepository.save(photoAlbum);
        if (!album.getPhotoList().isEmpty()){
            album.getPhotoList().forEach(k -> {
                Photo photo = new Photo();
                photo.setAreaId(album.getAreaId());
                photo.setAlbumId(photoAlbum.getId());
                photo.setResURL(k);
                photoRepository.save(photo);
            });
        }

        return null;
    }

    @Override
    @Transactional
    public PhotoAlbum update(PhotoAlbum album1){
        PhotoAlbum album = get(album1.getAreaId(), album1.getId(),album1.getType());

        boolean changed = false;
        if (StringUtils.isNotEmpty(album1.getTitle())){
            album.setTitle(album1.getTitle());
            changed = true;
        }

        if (StringUtils.isNotEmpty(album1.getContent())){
            album.setContent(album1.getContent());
            changed = true;
        }
        if (StringUtils.isNotEmpty(album1.getClassId())){
            album.setClassId(album1.getClassId());
            changed = true;
        }

        if (StringUtils.isNotEmpty(album1.getCover())){
            album.setCover(album1.getCover());
            changed = true;
        }

        if (album1.getSort() != null){
            album.setSort(album1.getSort());
            changed = true;
        }

        if (album1.getPrivated() != null){
            album.setPrivated(album1.getPrivated());
            changed = true;
        }

        if (StringUtils.isNotEmpty(album1.getChildrenId())){
            album.setChildrenId(album1.getChildrenId());
            changed = true;
        }
        if (album1.getType()!=null){
            album.setType(album1.getType());
            changed = true;
        }
        if(changed){
            photoAlbumRepository.save(album);
        }

        // 删除图片
        if (!album1.getPhotoList().isEmpty()){
            List<Photo> list = photoRepository.findAllByDeletedIsFalseAndAlbumId(album.getId());
            if (!list.isEmpty()){
                photoRepository.deleteAllByAlbumId(album.getId());
            }
            album1.getPhotoList().forEach(k -> {
                Photo photo = new Photo();
                photo.setAreaId(album.getAreaId());
                photo.setAlbumId(album.getId());
                photo.setResURL(k);
                photoRepository.save(photo);
            });
        }

        return album;
    }


    @Override
    public void delete(String areaId, String albumId) {
        PhotoAlbum ret = get(areaId, albumId,1);
        ret.setDeleted(true);
        photoAlbumRepository.save(ret);
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public void deleteAll(String areaId, String[] albumIds){
        if (albumIds == null || albumIds.length == 0){
            throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, "参数错误");
        }

        List<PhotoAlbum> albums = photoAlbumRepository.findAllByDeletedIsFalseAndAreaIdAndIdIn(areaId, albumIds);
        if (albums == null || albumIds.length != albums.size()){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "你猜什么东西错了?");
        }

        for (PhotoAlbum p : albums){
            if (StringUtils.isNotBlank(p.getChildrenId())){
                throw new BusinessException(ErrorCode.TARGET_CAN_NOT_CHANGE, "系统相册无法删除：" + p.getTitle());
            }
            p.setDeleted(true);
        }

        photoAlbumRepository.saveAll(albums);
    }

    /**
     * 查询相册名称列表
     * @param title
     * @return
     */
    @Override
    public List<PhotoAlbum> listByName(String areaId,String title) {
        if (StringUtils.isBlank(title)){
            return Collections.emptyList();
        }
        return photoAlbumRepository.searchAlbums(areaId,title);
    }
}
